Load all required libraries.

library(tidyverse)
## Warning: package 'tidyverse' was built under R version 3.6.3
## -- Attaching packages ---------------------------------------------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.2     v purrr   0.3.4
## v tibble  3.0.3     v dplyr   1.0.0
## v tidyr   1.1.0     v stringr 1.4.0
## v readr   1.3.1     v forcats 0.5.0
## Warning: package 'ggplot2' was built under R version 3.6.3
## Warning: package 'tibble' was built under R version 3.6.3
## Warning: package 'readr' was built under R version 3.6.3
## Warning: package 'dplyr' was built under R version 3.6.3
## Warning: package 'forcats' was built under R version 3.6.3
## -- Conflicts ------------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(plotly)
## Warning: package 'plotly' was built under R version 3.6.3
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(broom)
## Warning: package 'broom' was built under R version 3.6.3

Read in raw data from RDS.

raw_data <- readRDS("./n1_n2_cleaned_cases.rds")

Make a few small modifications to names and data for visualizations.

final_data <- raw_data %>% mutate(log_copy_per_L = log10(mean_copy_num_L)) %>%
  rename(Facility = wrf) %>%
  mutate(Facility = recode(Facility, 
                           "NO" = "WRF A",
                           "MI" = "WRF B",
                           "CC" = "WRF C"))

Seperate the data by gene target to ease layering in the final plot

#make three data layers
only_positives <<- subset(final_data, (!is.na(final_data$Facility)))
only_n1 <- subset(only_positives, target == "N1")
only_n2 <- subset(only_positives, target == "N2")
only_background <<-final_data %>% 
  select(c(date, cases_cum_clarke, new_cases_clarke, X7_day_ave_clarke, cases_per_100000_clarke)) %>%
  group_by(date) %>% summarise_if(is.numeric, mean)

#specify fun colors
background_color <- "#7570B3"
seven_day_ave_color <- "#E6AB02"
marker_colors <- c("N1" = '#1B9E77',"N2" ='#D95F02')

Build the main plot

      #first layer is the background epidemic curve
        p1 <- only_background %>%
              plotly::plot_ly() %>%
              plotly::add_trace(x = ~date, y = ~new_cases_clarke, 
                                type = "bar", 
                                hoverinfo = "text",
                                text = ~paste('</br> Date: ', date,
                                                     '</br> Daily Cases: ', new_cases_clarke),
                                alpha = 0.5,
                                name = "Daily Reported Cases",
                                color = background_color,
                                colors = background_color,
                                showlegend = FALSE) %>%
            layout(yaxis = list(title = "Clarke County Daily Cases", showline=TRUE)) %>%
            layout(legend = list(orientation = "h", x = 0.2, y = -0.3))
        
        #renders the main plot layer two as seven day moving average
        p1 <- p1 %>% plotly::add_trace(x = ~date, y = ~X7_day_ave_clarke, 
                             type = "scatter",
                             mode = "lines",
                             hoverinfo = "text",
                            text = ~paste('</br> Date: ', date,
                                                     '</br> Seven-Day Moving Average: ', X7_day_ave_clarke),
                             name = "Seven Day Moving Average Athens",
                             line = list(color = seven_day_ave_color),
                             showlegend = FALSE)
      

        
        #renders the main plot layer three as positive target hits
        
        p2 <- plotly::plot_ly() %>%
          plotly::add_trace(x = ~date, y = ~mean_copy_num_L,
                                       type = "scatter",
                                       mode = "markers",
                                       hoverinfo = "text",
                                       text = ~paste('</br> Date: ', date,
                                                     '</br> Facility: ', Facility,
                                                     '</br> Target: ', target,
                                                     '</br> Copies/L: ', round(mean_copy_num_L, digits = 2)),
                                       data = only_n1,
                                       symbol = ~Facility,
                                       marker = list(color = '#1B9E77', size = 8, opacity = 0.65),
                                       showlegend = FALSE) %>%
          plotly::add_trace(x = ~date, y = ~mean_copy_num_L,
                                       type = "scatter",
                                       mode = "markers",
                                       hoverinfo = "text",
                                       text = ~paste('</br> Date: ', date,
                                                     '</br> Facility: ', Facility,
                                                     '</br> Target: ', target,
                                                     '</br> Copies/L: ', round(mean_copy_num_L, digits = 2)),
                                       data = only_n2,
                                       symbol = ~Facility,
                                       marker = list(color = '#D95F02', size = 8, opacity = 0.65),
                                       showlegend = FALSE) %>%
            layout(yaxis = list(title = "SARS CoV-2 Copies/L", 
                                 showline = TRUE,
                                 type = "log",
                                 automargin = TRUE)) %>%
            layout(legend = list(orientation = "h", x = 0.2, y = -0.3))
        
        #adds the limit of detection dashed line
        p2 <- p2 %>% plotly::add_segments(x = as.Date("2020-03-14"), 
                                          xend = ~max(date + 10), 
                                          y = 3571.429, yend = 3571.429,
                                          opacity = 0.35,
                                          line = list(color = "black", dash = "dash")) %>%
          layout(annotations = list(x = as.Date("2020-03-28"), y = 3.8, xref = "x", yref = "y", 
                                    text = "Limit of Detection", showarrow = FALSE))

        

        p1
## Warning: `arrange_()` is deprecated as of dplyr 0.7.0.
## Please use `arrange()` instead.
## See vignette('programming') for more help
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_warnings()` to see where this warning was generated.
## Warning: Ignoring 1 observations
        p2
## Warning: `group_by_()` is deprecated as of dplyr 0.7.0.
## Please use `group_by()` instead.
## See vignette('programming') for more help
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_warnings()` to see where this warning was generated.

Combine the two main plot pieces as a subplot

p_combined <-
    plotly::subplot(p2,p1, # plots to combine, top to bottom
      nrows = 2,
      heights = c(.6,.4),  # relative heights of the two plots
      shareX = TRUE,  # plots will share an X axis
      titleY = TRUE
    ) %>%
    # create a vertical "spike line" to compare data across 2 plots
    plotly::layout(
      xaxis = list(
        spikethickness = 1,
        spikedash = "dot",
        spikecolor = "black",
        spikemode = "across+marker",
        spikesnap = "cursor"
      ),
      yaxis = list(spikethickness = 0)
    )
## Warning: Ignoring 1 observations
p_combined

Save the plot to pull into the index

save(p_combined, file = "./plotly_fig.rda")

Save an htmlwidget for website embedding

htmlwidgets::saveWidget(p_combined, "plotly_fig.html")

Build loess smoothing figures figures

#create smoothing data frames 
#n1
smooth_n1 <- only_n1 %>% select(-c(Facility)) %>% 
  group_by(date, cases_cum_clarke, new_cases_clarke, X7_day_ave_clarke, cases_per_100000_clarke) %>%
  summarize(sum_copy_num_L = sum(mean_total_copies)) %>%
  ungroup() %>%
  mutate(log_sum_copies_L = log10(sum_copy_num_L)) %>%
  mutate(target = "N1")
## `summarise()` regrouping output by 'date', 'cases_cum_clarke', 'new_cases_clarke', 'X7_day_ave_clarke' (override with `.groups` argument)
#n2
smooth_n2 <- only_n2 %>% select(-c(Facility)) %>% 
  group_by(date, cases_cum_clarke, new_cases_clarke, X7_day_ave_clarke, cases_per_100000_clarke) %>%
  summarize(sum_copy_num_L = sum(mean_total_copies)) %>%
  ungroup() %>%
  mutate(log_sum_copies_L = log10(sum_copy_num_L)) %>%
  mutate(target = "N2")
## `summarise()` regrouping output by 'date', 'cases_cum_clarke', 'new_cases_clarke', 'X7_day_ave_clarke' (override with `.groups` argument)
#add trendlines 
#extract data from geom_smooth
#n1 extract
extract_n1 <- ggplot(smooth_n1, aes(x = date, y = log_sum_copies_L)) + 
  stat_smooth(aes(outfit=fit_n1<<-..y..), method = "loess", color = '#1B9E77', span = 0.8)
## Warning: Ignoring unknown aesthetics: outfit
#n2 extract
extract_n2 <- ggplot(smooth_n2, aes(x = date, y = log_sum_copies_L)) + 
  stat_smooth(aes(outfit=fit_n2<<-..y..), method = "loess", color = '#1B9E77', span = 0.8)
## Warning: Ignoring unknown aesthetics: outfit
#look at the fits to align dates and total observations
#n1
extract_n1
## `geom_smooth()` using formula 'y ~ x'

fit_n1
##  [1]  9.609279  9.821338 10.025594 10.221991 10.410469 10.590973 10.763444
##  [8] 10.927824 11.083894 11.231475 11.370851 11.502317 11.626166 11.742694
## [15] 11.852193 11.955378 12.053518 12.145853 12.231462 12.309421 12.378807
## [22] 12.438699 12.488049 12.525701 12.552356 12.568992 12.576583 12.576107
## [29] 12.568539 12.553968 12.518279 12.461510 12.390536 12.312231 12.233470
## [36] 12.161129 12.101907 12.037807 11.957866 11.868679 11.776843 11.688952
## [43] 11.611603 11.551391 11.491474 11.407623 11.309863 11.208457 11.113669
## [50] 11.035761 10.984996 10.962828 10.950872 10.947463 10.952038 10.964037
## [57] 10.982900 11.008064 11.039344 11.078266 11.124997 11.179458 11.241572
## [64] 11.311261 11.388447 11.473123 11.565917 11.666789 11.775478 11.891721
## [71] 12.015255 12.145817 12.283153 12.427378 12.578666 12.737071 12.902644
## [78] 13.075437 13.255503 13.442893
#n2
extract_n2
## `geom_smooth()` using formula 'y ~ x'

fit_n2
##  [1]  9.480787  9.709230  9.930308 10.144012 10.350330 10.549251 10.740764
##  [8] 10.924858 11.101514 11.270717 11.432469 11.586775 11.733639 11.873067
## [15] 12.005061 12.130424 12.251504 12.367395 12.476905 12.578842 12.672015
## [22] 12.755230 12.828182 12.895952 12.958238 13.013442 13.059965 13.096210
## [29] 13.120578 13.130920 13.117455 13.082078 13.031328 12.971744 12.909866
## [36] 12.852234 12.805190 12.747798 12.668363 12.575156 12.476449 12.380514
## [43] 12.295623 12.230048 12.170120 12.092707 12.005093 11.914780 11.829271
## [50] 11.756067 11.702670 11.669123 11.639890 11.614790 11.594610 11.580136
## [57] 11.572155 11.571452 11.578160 11.589709 11.606257 11.628410 11.656772
## [64] 11.691949 11.734546 11.785031 11.842289 11.905902 11.975832 12.052036
## [71] 12.134475 12.223108 12.317896 12.418850 12.525991 12.639323 12.758850
## [78] 12.884574 13.016499 13.154630
#assign fits to a vector
n1_trend <- fit_n1
n2_trend <- fit_n2

#extract y min and max for each
limits_n1 <- ggplot_build(extract_n1)$data
## `geom_smooth()` using formula 'y ~ x'
limits_n1 <- as.data.frame(limits_n1)
n1_ymin <- limits_n1$ymin
n1_ymax <- limits_n1$ymax

limits_n2 <- ggplot_build(extract_n2)$data
## `geom_smooth()` using formula 'y ~ x'
limits_n2 <- as.data.frame(limits_n2)
n2_ymin <- limits_n2$ymin
n2_ymax <- limits_n2$ymax

#reassign dataframes (just to be safe)
work_n1 <- smooth_n1
work_n2 <- smooth_n2

#fill in missing dates to smooth fits
work_n1 <- work_n1 %>% complete(date = seq(min(date), max(date) +2, by = "1 day"))
date_vec_n1 <- work_n1$date
work_n2 <- work_n2 %>% complete(date = seq(min(date), max(date) +2, by = "1 day"))
date_vec_n2 <- work_n2$date

#create a new smooth dataframe to layer
smooth_frame_n1 <- data.frame(date_vec_n1, n1_trend, n1_ymin, n1_ymax)
smooth_frame_n2 <- data.frame(date_vec_n2, n2_trend, n2_ymin, n2_ymax)

#plot smooth frames
p3 <- plotly::plot_ly() %>%
  plotly::add_lines(x = ~date_vec_n1, y = ~n1_trend,
                    data = smooth_frame_n1,
                    hoverinfo = "text",
                    text = ~paste('</br> Date: ', date_vec_n1,
                                  '</br> Log Copies: ', round(n1_trend, digits = 2),
                                  '</br> Target: N1'),
                    line = list(color = '#1B9E77', size = 8, opacity = 0.65),
                    showlegend = FALSE) %>%
plotly::add_lines(x = ~date_vec_n2, y = ~n2_trend,
                  data = smooth_frame_n2,
                    hoverinfo = "text",
                    text = ~paste('</br> Date: ', date_vec_n2,
                                  '</br> Log Copies: ', round(n2_trend, digits = 2),
                                  '</br> Target: N2'),
                    line = list(color = '#D95F02', size = 8, opacity = 0.65),
                    showlegend = FALSE) %>%
plotly::add_ribbons(x ~date_vec_n1, ymin = ~n1_ymin, ymax = ~n1_ymax,
                    showlegend = FALSE,
                    opacity = 0.25,
                    hoverinfo = "text",
                    text = ~paste('</br> Date: ', date_vec_n1, #leaving in case we want to change
                                  '</br> Max Log Copies: ', round(n1_ymax, digits = 2),
                                  '</br> Min Log Copies: ', round(n1_ymin, digits = 2),
                                  '</br> Target: N1'),
                    name = "",
                    line = list(color = '#1B9E77')) %>%
plotly::add_ribbons(x ~date_vec_n2, ymin = ~n2_ymin, ymax = ~n2_ymax,
                    showlegend = FALSE,
                    opacity = 0.25,
                    hoverinfo = "text",
                    text = ~paste('</br> Date: ', date_vec_n2, #leaving in case we want to change
                                  '</br> Max Log Copies: ', round(n2_ymax, digits = 2),
                                  '</br> Min Log Copies: ', round(n2_ymin, digits = 2),
                                  '</br> Target: N2'),
                    name = "",
                    line = list(color = '#D95F02')) %>%
                layout(yaxis = list(title = "Total Log SARS CoV-2 Copies", 
                                 showline = TRUE,
                                 automargin = TRUE)) %>%
                layout(xaxis = list(title = "Date")) %>%
    plotly::add_segments(x = as.Date("2020-06-24"), 
                                          xend = as.Date("2020-06-24"), 
                                          y = ~min(n1_ymin), yend = ~max(n1_ymax),
                                          opacity = 0.35,
                                          name = "Bars Repoen",
                                          hoverinfo = "text",
                                          text = "</br> Bars Reopen",
                                                 "</br> 2020-06-24",
                                          showlegend = FALSE,
                                          line = list(color = "black", dash = "dash")) %>%
    plotly::add_segments(x = as.Date("2020-07-09"), 
                                          xend = as.Date("2020-07-09"), 
                                          y = ~min(n1_ymin), yend = ~max(n1_ymax),
                                          opacity = 0.35,
                                          name = "Mask Mandate",
                                          hoverinfo = "text",
                                          text = "</br> Mask Mandate",
                                                 "</br> 2020-07-09",
                                          showlegend = FALSE,
                                          line = list(color = "black", dash = "dash")) %>%
    plotly::add_segments(x = as.Date("2020-08-20"), 
                                          xend = as.Date("2020-08-20"), 
                                          y = ~min(n1_ymin), yend = ~max(n1_ymax),
                                          opacity = 0.35,
                                          name = "</br> Classes Begin",
                                                 "</br> 2020-08-20",
                                          hoverinfo = "text",
                                          text = "Classes Begin",
                                          showlegend = FALSE,
                                          line = list(color = "black", dash = "dash"))

p3

Create final trend plot by stacking with epidemic curve

smooth_extract <-
    plotly::subplot(p3,p1, # plots to combine, top to bottom
      nrows = 2,
      heights = c(.6,.4),  # relative heights of the two plots
      shareX = TRUE,  # plots will share an X axis
      titleY = TRUE
    ) %>%
    # create a vertical "spike line" to compare data across 2 plots
    plotly::layout(
      xaxis = list(
        spikethickness = 1,
        spikedash = "dot",
        spikecolor = "black",
        spikemode = "across+marker",
        spikesnap = "cursor"
      ),
      yaxis = list(spikethickness = 0)
    )
## Warning: Ignoring 1 observations
smooth_extract
save(smooth_extract, file = "./smooth_extract.rda")